package com.stefan.service.impl;

import com.mongodb.client.result.DeleteResult;
import com.stefan.entity.Product;
import com.stefan.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
@Component
public class ProductServiceImpl implements ProductService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void addProduct(Product product) {
        // 将商品信息存入MongoDB
        Product save = mongoTemplate.insert(product);
        System.out.println("商品添加成功: " + save);
    }
    @Override
    public void updateProduct(Product product) {
        // 更新商品信息
        // save: _id存在时更新数据
        //mongoTemplate.save(employee);
        // insert： _id存在抛出异常 支持批量操作
        Product save = mongoTemplate.save(product);
        System.out.println("商品更新成功: " + save);
    }

    @Override
    public Product getProduct(Integer productId) {
        // 从MongoDB中获取商品信息
        return mongoTemplate.findById(productId, Product.class);
    }

    @Override
    public List<Product> getAllProducts() {
        // 获取所有商品信息
        return mongoTemplate.findAll(Product.class);
    }

    @Override
    public void deleteProduct(Integer productId) {
        // 从MongoDB中删除商品信息
//        DeleteResult remove = mongoTemplate.remove(mongoTemplate.findById(productId, Product.class));
//        System.out.println("商品删除成功: " + remove.getDeletedCount() + " items deleted");
        Query query = new Query(Criteria.where("_id").is(productId));
        DeleteResult result = mongoTemplate.remove(query, Product.class);
        System.out.println("商品删除成功: " + result.getDeletedCount() + " items deleted");
    }

    @Override
    public void addProducts(List<Product> products) {
        Collection<Product> insert = mongoTemplate.insert(products, Product.class);
        if (insert != null && !insert.isEmpty()) {
            System.out.println("批量添加商品成功: " + insert.size() + " items");
        } else {
            System.out.println("批量添加商品失败或无商品添加");
        }
    }
}
